<?php

class UserareaController extends Zend_Controller_Action {

    public function preDispatch() {

        if (!defined('PAGE_ID'))
            $this->_redirect(SITE_URL);
    }

    public function indexAction() {
        $action = $this->getRequest()->getParam('view', '');
        if ($action == '') {
            if (USER_ID > 0) {
                $action = 'info';
                $this->info();
            } else {
                $action = 'login';
                $this->login();
            }
        } else {
            $this->$action();
        }
        $this->view->action = $action;
    }

    /**
     * Авторизация
     */
    public function login() {
        $forms = new AclForm();
        $model = new AclModel();
        $form = $forms->Login(SITE_URL . PAGE_URL);
        $this->view->form = $form;
        $t = Zend_Registry::get('Zend_Locale');

        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if (!$model->authentification($formData['login'], $formData['password'])) {
                $this->view->error = $t->_('Sorry, unrecognized username or password.');
            } else {
                $this->_redirect(SITE_URL);
            }
        }
    }

    /**
     * Выход
     */
    public function logout() {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect(SITE_URL);
    }

    /**
     * Просмотр профиля
     */
    public function info() {

    }

    /**
     * Редактирование профиля
     */
    public function profile() {
        $model = new AclModel();
        $forms = new AclForm();
        $form = $forms->Profile(USER_ID);
        $user = $model->getUsers(USER_ID);
        $form->populate((array) $user);
        $this->view->form = $form;
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if (isset($formData['MAX_FILE_SIZE']))
                unset ($formData['MAX_FILE_SIZE']);

            if (file_exists($_FILES["photo"]["tmp_name"])){
                $image = new ImagesModel();
                $upload = $image->updatePhoto($_FILES["photo"]["tmp_name"], USER_ID);
                if (!$upload){
                    $t = Zend_Registry::get('Zend_Locale');
                    $form->getElement('photo')->addError($t->_('Upload failed'));
                }
            }
            if ($form->isValid($formData)) {
                array_pop($formData);
                $formData['login'] = $user->login;
                $model->updateUser($formData, USER_ID);
                $this->_redirect(SITE_URL . PAGE_URL . '/view/profile');
            } else {
                $formData['login'] = $user->login;
                $form->populate($formData);
            }
        }
    }

    /**
     * Авторизация
     */
    public function activation() {
        $salt = (string) $this->getRequest()->getParam('salt', '');
        $model = new AclModel();
        if ($salt <> '') {
            $model->activateUser($salt);
        }
    }

    /**
     * Регистрация
     */
    public function register() {
        $t = Zend_Registry::get('Zend_Locale');
        $model = new AclModel();
        $forms = new UserareaForm();
        $form = $forms->register();
        $this->view->form = $form;
        $this->view->formvalid = false;
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if ($form->isValid($formData)) {
                array_pop($formData);
                array_pop($formData);

                $user = $model->getUsers($model->updateUser($formData));

                $mail = new MailModel();
                $template = $mail->getTemplates('confirm_registration');
                $url = SITE_URL . PAGE_URL . '/view/activation/salt/' . $user->salt;
                $template = str_replace('{{{password}}}', $formData['password'], $template['confirm_registration']);
                $template = str_replace('{{{login}}}', $user->login, $template);
                $template = str_replace('{{{name}}}', $user->name, $template);
                $template = str_replace('{{{url}}}', $url, $template);
                $template = str_replace('{{{site_title}}}', SITE_TITLE, $template);
                $body = str_replace('{{{site_url}}}', SITE_URL, $template);
                $mail->sendMail($user->email, $t->_('Successful registration'), $body);

                $this->view->formvalid = true;
            } else {
                $form->populate($formData);
            }
        }
    }

    /**
     * Запрос пароля
     */
    public function request() {
        $forms = new AclForm();
        $model = new AclModel();
        $form = $forms->Request(SITE_URL . PAGE_URL . '/view/request');

        $t = Zend_Registry::get('Zend_Locale');

        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if ($form->isValid($formData)) {
                $email = $formData['email'];
                $user = $model->getUserByEmail($email);
                if (isset($user->salt)) {
                    $mail = new MailModel();
                    $template = $mail->getTemplates('confirm_password');
                    $url = SITE_URL . PAGE_URL . '/view/password/salt/' . $user->salt;
                    $template = str_replace('{{{login}}}', $user->login, $template['confirm_password']);
                    $template = str_replace('{{{name}}}', $user->name, $template);
                    $template = str_replace('{{{url}}}', $url, $template);
                    $template = str_replace('{{{site_title}}}', SITE_TITLE, $template);
                    $body = str_replace('{{{site_url}}}', SITE_URL, $template);
                    $mail->sendMail($user->email, $t->_('Confirm new password'), $body);
                    $this->view->formvalid = true;
                } else {
                    $form->email->addError($t->_("E-mail not found"));
                    $form->populate($formData);
                }
            } else {
                $form->populate($formData);
            }
        }
        $this->view->form = $form;
    }

    /**
     * Сброс пароля
     */
    public function password() {
        $salt = (string) $this->getRequest()->getParam('salt', '');
        $model = new AclModel();
        $user = $model->getUserBySalt($salt);
        $t = Zend_Registry::get('Zend_Locale');
        if (isset($user->id)) {
            $mail = new MailModel();
            $template = $mail->getTemplates('new_password');
            $password = $model->updatePassword($user->id);
            $url = SITE_URL . PAGE_URL . '/view/password/salt/' . $user->salt;
            $template = str_replace('{{{password}}}', $password, $template['new_password']);
            $template = str_replace('{{{login}}}', $user->login, $template);
            $template = str_replace('{{{name}}}', $user->name, $template);
            $template = str_replace('{{{url}}}', $url, $template);
            $template = str_replace('{{{site_title}}}', SITE_TITLE, $template);
            $body = str_replace('{{{site_url}}}', SITE_URL, $template);
            $mail->sendMail($user->email, $t->_('New password'), $body);
            $this->view->formvalid = true;
        }
    }

    /**
     * Редактирование секции
     */
    public function modifyAction() {
        //Настриваем почтовые шаблоны
        $forms = new UserareaForm();
        $form = $forms->templates();
        $this->view->form = $form;
        $model = new MailModel();
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if ($form->isValid($formData)) {
                array_pop($formData);
                $model->updateTemplates($formData);
            } else {
                $form->populate($formData);
            }
        } else {
            $templates = $model->getTemplates();
            $form->populate($templates);
            //print_r($templates);
        }
    }

    /**
     * Добавление секции
     */
    public function addAction() {
        $pid = (int) $this->getRequest()->getParam('pid', 0);
        $this->_redirect('/pages/section/id/' . $pid);
    }

}
